﻿package com.shuqi.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Random;

import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.SharedPreferenceUtil;

/**
 * ConfigVersion主类
 * 
 * @author Arthur Jin
 * @version 3.1
 */
public class ConfigVersion {
    // @Deprecated
    // /**测试IMEI*/
    // private static final String TEST_IMEI = "TESTIMEI_ishuqi1004";//TODO 测试IMEI

    /** ConfigVersion */
    private static String VERSION;
    /** cellid */
    public static int CELLID = -1;
    /** IMEI */
    public static String IMEI = "";
    /** lacid */
    public static int LAC = -1;
    /** 与placeid同理 */
    public static String ANSITEID = "";
    /** android版本 */
    public static String SDK = "";
    /** 手机型号 */
    public static String MODEL = "";
    /** 手机厂商 */
    public static String MANUFACTURER = "";
    /** 手机品牌 */
    public static String BRAND = "";
    /** IMSI */
    public static String IMSI = "";
    /** 自定义加密字符串 */
    public static String ENC = "";
    /** 自定义SN */
    public static String SN = "";
    /** 手机屏幕宽高 */
    public static String WH = "";
    /** fr id */
    public static String FR = "xxxx";
    /** klink id */
    public static String KLINK = "xxxx";
    /** vc */
    public static String VC = "";
    /** 网络类型 */
    public static String NET_TYPE = "";
    /** 日期类型的版本号 */
    public static String mVERSION_INFO;
    /** 客户端可视化版本号:8.0.1 */
    public static String mAppVerName;
    /** softid */
    private static String mSOFTID;
    /** 软件的minSdkVersion */
    private static String mMIN_SDK_VERSION;
    /** enc的加密key */
    private static long mENC_KEY;
    /** 用户的userid */
    private static String mUSERID;
    private static String session;
    /** 上一版本号 */
    public static String PRE_VERSIONINFO;
    /** 上一版本placeid */
    public static String PRE_PLACEID;
    /** 第一个版本的placeid */
    public static String FIRST_PLACEID;
    /** 更新当前placeid之前的当前placeid */
    public static String UN_UPDATED_PLACEID;
    /** 更新当前version之前的当前version */
    public static String UN_UPDATED_VERSION;
    /** 本机ip */
    public static String IP;
    /** imei的加密串 */
    private static String AppApiKey;

    /** mac地址参数 */
    private static String MAC;

    /** 获取ConfigVersion */
    public static String getVersion() {
        setVersion(mVERSION_INFO, mSOFTID, mMIN_SDK_VERSION);
        return VERSION;
    }

    /**
     * 获取ConfigVersion信息
     * 
     * @remark 根据规则传递不同的type附加不同的ConfigVersion信息
     * @param type 0-->return softID+Version；1-->return softID+Version+placeid
     * @return
     */
    public static String getVersionByType(int type) {
        String verInfo = mSOFTID + "_" + mVERSION_INFO;
        if (type == 0) {
            verInfo = mSOFTID + "_" + mVERSION_INFO;
        } else if (type == 1) {
            verInfo = mSOFTID + "_" + mVERSION_INFO + "_" + FIRST_PLACEID;
        }
        return verInfo;
    }

    public static boolean hasNull() {
        return TextUtils.isEmpty(SN) || TextUtils.isEmpty(ENC) || TextUtils.isEmpty(IMEI);
    }

    /**
     * 初始化部分Version
     * 
     * @param version_info 日期类型的版本号
     * @param softid softid
     * @param min_sdk_version 软件的minSdkVersion
     */
    private static void setVersion(String version_info, String softid, String min_sdk_version) {
        String fr_or_klink = "";
        if (ConfigVersion.FR != null && !"".equals(ConfigVersion.FR)
                && !"xxxx".equals(ConfigVersion.FR)) {
            fr_or_klink = "&fr=" + ConfigVersion.FR;
        } else if (ConfigVersion.KLINK != null && !"".equals(ConfigVersion.KLINK)
                && !"xxxx".equals(ConfigVersion.KLINK)) {
            fr_or_klink = "&klink=" + ConfigVersion.KLINK;
        }
        VERSION =
                ("soft_id=" + softid + "&ver=" + version_info + "&appVer=" + mAppVerName
                        + "&platform=an&placeid=" + ANSITEID + fr_or_klink + "&imei=" + IMEI
                        + "&mac=" + MAC + "&cellid=" + CELLID + "&lac=" + LAC + "&sdk=" + SDK
                        + "&wh=" + WH + "&imsi=" + IMSI + "&msv=" + min_sdk_version + "&enc="
                        + getEnc(mENC_KEY) + "&sn=" + SN + "&vc=" + ConfigVersion.VC + "&mod="
                        + MODEL + "&manufacturer=" + MANUFACTURER + "&brand=" + BRAND
                        + "&net_type=" + NET_TYPE + "&first_placeid=" + FIRST_PLACEID + "&aak="
                        + AppApiKey + (TextUtils.isEmpty(mUSERID) ? "" : ("&user_id=" + mUSERID)) + (TextUtils
                        .isEmpty(session) ? "" : ("&session=" + session))).replaceAll(" ", "");
    }

    /**
     * 初始化全部Version
     * 
     * @param context Context
     * @param root_path 软件的sdcard中文件夹的根路径
     * @param version_info 日期类型的版本
     * @param soft_id soft_id
     * @param min_sdk_version 软件的minSdkVersion
     * @param enc_key enc的加密key
     * @param userid 用户的userdid
     */
    public static void setTelInfos(Context context, String root_path, String version_info,
            String soft_id, String min_sdk_version, long enc_key, String userid, String session) {
        String placeid_id = "xxxx";
        String fr_id = "xxxx";
        String klink_id = "xxxx";
        try {
            Properties p = new Properties();
            p.load(context.getAssets().open("config/config.ini"));
            placeid_id = p.getProperty("placeid");
            fr_id = p.getProperty("fr");
        } catch (Exception e2) {
            e2.printStackTrace();
        }

        try {
            mVERSION_INFO = URLEncoder.encode(version_info, HTTP.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            mSOFTID = URLEncoder.encode(soft_id, HTTP.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            mMIN_SDK_VERSION = URLEncoder.encode(min_sdk_version, HTTP.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mENC_KEY = enc_key;
        try {
            ANSITEID = URLEncoder.encode(placeid_id, HTTP.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }

        SharedPreferences sp = context.getSharedPreferences("ConfigVersion", Context.MODE_PRIVATE);
        // 计算srcplaceid
        String firstPlaceid = sp.getString("firstplaceid", null);
        if (TextUtils.isEmpty(firstPlaceid)) {
            Editor editor = sp.edit();
            editor.putString("firstplaceid", ANSITEID);
            editor.commit();
            FIRST_PLACEID = "src" + ANSITEID;
        } else {
            FIRST_PLACEID = "src" + firstPlaceid;
        }
        try {
            FIRST_PLACEID = URLEncoder.encode(FIRST_PLACEID, HTTP.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String prePlaceid = sp.getString("preplaceid", null);
        String curPlaceid = sp.getString("curplaceid", null);
        if (UN_UPDATED_PLACEID == null) {
            UN_UPDATED_PLACEID = curPlaceid;
        }
        if (TextUtils.isEmpty(prePlaceid)) {
            Editor editor = sp.edit();
            editor.putString("preplaceid", ANSITEID);
            editor.putString("curplaceid", ANSITEID);
            editor.commit();
            PRE_PLACEID = ANSITEID;
        } else if (ANSITEID != null && !ANSITEID.equals(curPlaceid)) {
            Editor editor = sp.edit();
            editor.putString("preplaceid", curPlaceid);
            editor.putString("curplaceid", ANSITEID);
            editor.commit();
            PRE_PLACEID = curPlaceid;
        } else {
            PRE_PLACEID = prePlaceid;
        }

        String preVersion = sp.getString("preversion", null);
        String curVersion = sp.getString("curversion", null);
        if (UN_UPDATED_VERSION == null) {
            UN_UPDATED_VERSION = curVersion;
        }
        if (TextUtils.isEmpty(preVersion)) {
            Editor editor = sp.edit();
            editor.putString("preversion", version_info);
            editor.putString("curversion", version_info);
            editor.commit();
            PRE_VERSIONINFO = version_info;
        } else if (version_info != null && !version_info.equals(curVersion)) {
            Editor editor = sp.edit();
            editor.putString("preversion", curVersion);
            editor.putString("curversion", version_info);
            editor.commit();
            PRE_VERSIONINFO = curVersion;
        } else {
            PRE_VERSIONINFO = preVersion;
        }
        // 获取手机sn
        try {
            ConfigVersion.SN = URLEncoder.encode(getSN(), HTTP.UTF_8);
        } catch (Exception e1) {
        }
        // 获取imei等参数
        TelephonyManager tm =
                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        int type = tm.getNetworkType();
        if (type == TelephonyManager.NETWORK_TYPE_EDGE
                || type == TelephonyManager.NETWORK_TYPE_GPRS
                || type == TelephonyManager.NETWORK_TYPE_UMTS) {
            try {
                GsmCellLocation location = (GsmCellLocation) tm.getCellLocation();
                if (location != null) {
                    ConfigVersion.CELLID = location.getCid();
                    ConfigVersion.LAC = location.getLac();
                } else {
                    ConfigVersion.CELLID = -1;
                    ConfigVersion.LAC = -1;
                }
            } catch (Exception e) {
                ConfigVersion.CELLID = -1;
                ConfigVersion.LAC = -1;
                // e.printStackTrace();
            }
        } else {
            try {
                ConfigVersion.CELLID = type;// location.getNetworkId();
                ConfigVersion.LAC = -1;// location.getSystemId();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 获取IMEI
        try {
            ConfigVersion.IMEI = tm.getDeviceId();
            if (!TextUtils.isEmpty(ConfigVersion.IMEI)) {
                ConfigVersion.IMEI = URLEncoder.encode(ConfigVersion.IMEI, HTTP.UTF_8);
            } else {
                if (TextUtils.isEmpty(SN)) {
                    ConfigVersion.IMEI = "null";
                } else {
                    ConfigVersion.IMEI = SN;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ConfigVersion.IMEI = SN;
        }
        // ConfigVersion.IMEI = TEST_IMEI;//TODO 测试IMEI
        // 获取IMSI
        try {
            ConfigVersion.IMSI = tm.getSubscriberId();
            if (!TextUtils.isEmpty(ConfigVersion.IMSI)) {
                ConfigVersion.IMSI = URLEncoder.encode(ConfigVersion.IMSI, HTTP.UTF_8);
            } else {
                ConfigVersion.IMSI = "null";
            }
        } catch (Exception e) {
            e.printStackTrace();
            ConfigVersion.IMSI = "null";
        }
        // 当前sdk版本
        try {
            ConfigVersion.SDK = URLEncoder.encode(android.os.Build.VERSION.SDK, HTTP.UTF_8);
        } catch (Exception e) {

        }
        // 手机型号、手机厂商、手机品牌
        try {
            ConfigVersion.MODEL = URLEncoder.encode(android.os.Build.MODEL, HTTP.UTF_8);
            ConfigVersion.MANUFACTURER =
                    URLEncoder.encode(android.os.Build.MANUFACTURER, HTTP.UTF_8);
            ConfigVersion.BRAND = URLEncoder.encode(android.os.Build.BRAND, HTTP.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // ConfigVersion.ENC = getEnc(enc_key);
        // 获取手机屏幕分辨率
        if (context instanceof Activity) {
            DisplayMetrics dm = new DisplayMetrics();
            ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenH = dm.heightPixels;
            int screenW = dm.widthPixels;
            ConfigVersion.WH = screenW + "x" + screenH;
        } else if (TextUtils.isEmpty(ConfigVersion.WH)) {
            ConfigVersion.WH = "";
        }
        // 9000和8000渠道相关参数
        String frXml = fr_id;
        String frDatabase = sp.getString("fr_1", "");
        String klinkXml = klink_id;
        String klinkDatabase = sp.getString("klink_1", "");

        if (!TextUtils.isEmpty(frDatabase) && !"xxxx".equals(frDatabase)) {
            ConfigVersion.FR = frDatabase;
        } else if (TextUtils.isEmpty(frDatabase) && !TextUtils.isEmpty(frXml)
                && !"xxxx".equals(frXml)) {
            Editor ed = sp.edit();
            ed.putString("fr_1", frXml);
            ed.commit();
            ConfigVersion.FR = frXml;
        }

        if (!TextUtils.isEmpty(klinkDatabase) && !"xxxx".equals(klinkDatabase)) {
            ConfigVersion.KLINK = klinkDatabase;
        } else if (TextUtils.isEmpty(klinkDatabase) && !TextUtils.isEmpty(klinkXml)
                && !"xxxx".equals(klinkXml)) {
            Editor ed = sp.edit();
            ed.putString("klink_1", klinkXml);
            ed.commit();
            ConfigVersion.KLINK = klinkXml;
        }
        // 计算vc验证
        // vc = md5(imei+imsi+sn) 110630
        try {
            char HEX_DIGITS[] =
                    {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(((ConfigVersion.IMEI == null ? "" : ConfigVersion.IMEI)
                    + (ConfigVersion.IMSI == null ? "" : ConfigVersion.IMSI) + (ConfigVersion.SN == null ? ""
                    : ConfigVersion.SN)).getBytes());
            byte[] b = md5.digest();
            StringBuilder sb = new StringBuilder(b.length * 2);
            for (int i = 0; i < b.length; i++) {
                sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
                sb.append(HEX_DIGITS[b[i] & 0x0f]);
            }
            String s = sb.toString().toLowerCase();
            ConfigVersion.VC =
                    "" + s.charAt(s.length() - 1) + s.charAt(s.length() - 3)
                            + s.charAt(s.length() - 6) + s.charAt(s.length() - 9);
            ConfigVersion.VC = URLEncoder.encode(ConfigVersion.VC, HTTP.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!"xxxx".equals(userid)) {
            mUSERID = userid;
        }

        ConfigVersion.session = session;

        // 设置imei的加密串
        getAppApiKey();

        try {
            // 判断当前网络类型
            ConnectivityManager manager =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netWorkInfo = manager.getActiveNetworkInfo();
            if (netWorkInfo == null || !netWorkInfo.isAvailable()) {
                NET_TYPE = "";
            } else if (netWorkInfo.getTypeName().equalsIgnoreCase("MOBILE")) {
                NET_TYPE = netWorkInfo.getExtraInfo();
                if (!TextUtils.isEmpty(NET_TYPE)) {
                    NET_TYPE = NET_TYPE.replaceAll("&", "");
                }
            } else if (netWorkInfo.getTypeName().equalsIgnoreCase("WIFI")) {
                NET_TYPE = "wifi";
            } else {
                NET_TYPE = "other";
            }
            if (!TextUtils.isEmpty(NET_TYPE)) {
                NET_TYPE = URLEncoder.encode(NET_TYPE, HTTP.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (PropertiesUtils.isMacAddSwitchLocalOpen(context, false)) {
            try {
                // 获取mac地址
                WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo info = wifi.getConnectionInfo();
                MAC = info.getMacAddress();
                if (!TextUtils.isEmpty(MAC)) {
                    MAC = URLEncoder.encode(MAC, HTTP.UTF_8);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 获取ip 暂未使用
        // IP = GetIpAddress();

        try {
            String packageName = context.getPackageName();
            PackageInfo appInfo =
                    context.getPackageManager().getPackageInfo(packageName,
                            PackageManager.GET_INSTRUMENTATION);
            if (appInfo != null) {
                mAppVerName = appInfo.versionName;
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            mAppVerName = "";
        }
    }

    /**
     * 获取imei的加密串
     */
    public static String getAppApiKey() {
        if (TextUtils.isEmpty(AppApiKey)) {
            try {
                final int[] p1 = {1, 3, 8, 11};// imei位数
                final int[] p2 = {2, 3, 4, 8, 16, 21};// MD5位数
                final String keyStr = "cad458ec";

                String temp = "";

                if (ConfigVersion.IMEI != null && ConfigVersion.IMEI.length() > 11) {

                    temp += IMEI.charAt(p1[0]);
                    temp += IMEI.charAt(p1[1]);
                    temp += IMEI.charAt(p1[2]);
                    temp += IMEI.charAt(p1[3]);

                    temp += keyStr;

                    temp = MD5(temp);

                    AppApiKey =
                            "" + temp.charAt(p2[0]) + temp.charAt(p2[1]) + temp.charAt(p2[2])
                                    + temp.charAt(p2[3]) + temp.charAt(p2[4]) + temp.charAt(p2[5]);
                    AppApiKey = URLEncoder.encode(AppApiKey, HTTP.UTF_8);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return AppApiKey;
    }

    private static final String MD5(String s) {// MD5编码
        try {
            byte[] btInput = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < md.length; i++) {
                int val = ((int) md[i]) & 0xff;
                if (val < 16)
                    sb.append("0");
                sb.append(Integer.toHexString(val));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 判断是否更新了软件
     */
    public static boolean isApkUpdated(Context context) {
        try {
            SharedPreferences sp =
                    context.getSharedPreferences("ConfigVersion", Context.MODE_PRIVATE);
            if (sp.getBoolean("need2upload", false)) {
                return true;
            }
            if (!ANSITEID.equals(UN_UPDATED_PLACEID) || !mVERSION_INFO.equals(UN_UPDATED_VERSION)) {
                Editor editor = sp.edit();
                editor.putBoolean("need2upload", true);
                editor.commit();
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    /**
     * 通知此次上传信息已完成
     */
    public static void hasApkUpdatedDone(Context context) {
        try {
            SharedPreferences sp =
                    context.getSharedPreferences("ConfigVersion", Context.MODE_PRIVATE);
            Editor editor = sp.edit();
            editor.putBoolean("need2upload", false);
            editor.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取本机ip
     */
    public static String GetIpAddress() {
        Enumeration<NetworkInterface> netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    InetAddress ip = ips.nextElement();
                    if (!ip.isLoopbackAddress() && ip instanceof Inet4Address) {
                        return ip.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    // /**
    // * 获取SN
    // * @param rootpath 软件的sdcard中文件夹的根路径
    // * @return SN值
    // */
    // private static String getSN(String rootpath, Context context) {
    // String sn = null;
    // SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
    // sn = sp.getString("sn", null);
    // if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
    // .getExternalStorageState())) {// SD卡可用时
    // File shuqiFolder = new File(rootpath);
    // if (!shuqiFolder.exists())
    // shuqiFolder.mkdirs();
    // File snFile = new File(rootpath + "/sn");// 1.4 修改sn文件名
    // if (!snFile.exists()) {// 文件不存在时
    // if (TextUtils.isEmpty(sn)) {// sp中没有sn时
    // sn = System.currentTimeMillis()
    // + (new Random(System.nanoTime()).nextInt(1000) + 1000 + "")
    // .substring(1);
    // Editor editor = sp.edit();
    // editor.putString("sn", sn);
    // editor.commit();
    // }
    // try {
    // snFile.createNewFile();
    // FileOutputStream fos = new FileOutputStream(snFile);
    // byte[] bytes = sn.getBytes();
    // fos.write(bytes);
    // fos.close();
    // } catch (Exception e) {
    // Log4an.e("zyc.ConfigVersion", "save sn to file err");
    // }
    //
    // } else {// 文件存在时
    // try {
    // FileReader fr = new FileReader(snFile);
    // BufferedReader br = new BufferedReader(fr);
    // String snFromFile = br.readLine();
    // if (TextUtils.isEmpty(sn) || !sn.equals(snFromFile)) {
    // Editor editor = sp.edit();
    // editor.putString("sn", snFromFile);
    // editor.commit();
    // sn = snFromFile;
    // } else {
    // sn = snFromFile;
    // }
    // br.close();
    // fr.close();
    // } catch (Exception e) {
    // Log4an.e("zyc.ConfigVersion", "read sn from file err");
    // }
    // if (TextUtils.isEmpty(sn)) {
    // if (snFile.delete()) {
    // return getSN(rootpath, context);
    // }
    // }
    // }
    // /* 1.4 */
    // snFile = new File(rootpath + "/sn.shuqi");
    // if (snFile.exists()) {
    // snFile.delete();
    // }
    // }
    // return checkSN(rootpath, context, sn);
    // }
    //
    // /**
    // * 检查sn,不符合规则则重置
    // * @param rootpath 软件的sdcard中文件夹的根路径
    // * @return SN值
    // */
    // private static String checkSN(String rootpath, Context context, String sn) {
    // if (sn != null && sn.length() > 4 && sn.matches("[0-9]+")) {
    // return sn;
    // }
    //
    // SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
    // sn = System.currentTimeMillis()
    // + (new Random(System.nanoTime()).nextInt(1000) + 1000 + "").substring(1);
    // Editor editor = sp.edit();
    // editor.putString("sn", sn);
    // editor.commit();
    // try {
    // if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
    // .getExternalStorageState())) {// SD卡可用时
    // File shuqiFolder = new File(rootpath);
    // if (!shuqiFolder.exists())
    // shuqiFolder.mkdirs();
    // File snFile = new File(rootpath + "/sn");// 1.4 修改sn文件名
    // if (snFile.exists()) {// 文件不存在时
    // snFile.delete();
    // }
    // snFile.createNewFile();
    // FileOutputStream fos = new FileOutputStream(snFile);
    // byte[] bytes = sn.getBytes();
    // fos.write(bytes);
    // fos.close();
    // }
    // } catch (Exception e) {
    // Log4an.e("zyc.ConfigVersion", "save sn to file err");
    // }
    // return sn;
    // }

    /**
     * 获取加密字符串enc
     * 
     * @param enc_key enc的加密key
     * @return enc字符串
     */
    private static String getEnc(long enc_key) {
        try {
            long curTime = System.currentTimeMillis();
            String c = Long.toString(curTime);
            /*---1.5---*/
            if (c.length() < 13) {
                int length = c.length();
                for (int i = 0; i < 13 - length; i++) {
                    c = "2" + c;
                }
            } else if (c.length() > 13) {
                c = c.substring(0, 13);
            }

            String d =
                    c.substring(1, 2) + c.substring(3, 4) + c.substring(5, 6) + c.substring(8, 9)
                            + c.substring(6, 7);
            long e = 12347 * (enc_key == 0 ? 24697L : enc_key);
            if (0 != Integer.parseInt(d)) {
                e = Long.parseLong(d) * (enc_key == 0 ? 24697L : enc_key);
            }
            String f = Long.toString(e);
            String g = f.substring(f.length() - 5, f.length());
            return URLEncoder.encode(g + c, HTTP.UTF_8);
        } catch (Exception e) {
            return "";
        }
    }

    private static final String SD_ROOT_FILENAME = "/.a8a3_1944_91d5_aa08_18b0"; // 该串为随机产生的串，作为sd卡根目录下文件名

    public static String getSN() {
        String appSn = null; // sd应用目录下sn
        String spSn = null; // SharedPreferences 下sn
        String sdSn = null; // sd卡根目录下sn

        spSn = readSpSn();

        String sdPath = getSDPath();
        if (!TextUtils.isEmpty(sdPath)) {
            appSn = readSdFileSn(Config.ROOT_PATH, "/sn");
            sdSn = readSdFileSn(sdPath, SD_ROOT_FILENAME);
        }

        return reSetSn(appSn, spSn, sdSn, sdPath);
    }

    private static String reSetSn(String appSn, String spSn, String sdSn, String sdPath) {
        String resultSN = null;

        if (checkSn(spSn)) {
            resultSN = spSn;
        }
        if (checkSn(appSn)) {
            if (resultSN != null && !resultSN.equals(appSn)) {
                appSn = null;
            } else {
                resultSN = appSn;
            }
        }
        if (checkSn(sdSn)) {
            if (resultSN != null && !resultSN.equals(sdSn)) {
                sdSn = null;
            } else {
                resultSN = sdSn;
            }
        }


        if (resultSN != null) {
            if (!checkSn(appSn)) {
                if (!TextUtils.isEmpty(sdPath)) {
                    writeSdFileSn(Config.ROOT_PATH, "/sn", resultSN);
                }
            }
            if (!checkSn(sdSn)) {
                if (!TextUtils.isEmpty(sdPath)) {
                    writeSdFileSn(sdPath, SD_ROOT_FILENAME, resultSN);
                }
            }
            if (!checkSn(spSn)) {
                writeSpSn(resultSN);
            }
        } else {
            resultSN =
                    System.currentTimeMillis()
                            + (new Random(System.nanoTime()).nextInt(1000) + 1000 + "")
                                    .substring(1);
            writeSpSn(resultSN);
            if (!TextUtils.isEmpty(sdPath)) {
                writeSdFileSn(Config.ROOT_PATH, "/sn", resultSN);
                writeSdFileSn(sdPath, SD_ROOT_FILENAME, resultSN);
            }
        }
        return resultSN;
    }

    private static void writeSpSn(String sn) {
        SharedPreferences sp =
                ShuqiApplication.getContext().getSharedPreferences(SharedPreferenceUtil.SP_NAME_CONFIG, Context.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putString("sn", sn);
        editor.commit();
    }

    private static String readSpSn() {
        String sn = null;
        SharedPreferences sp =
                ShuqiApplication.getContext().getSharedPreferences(SharedPreferenceUtil.SP_NAME_CONFIG, Context.MODE_PRIVATE);
        sn = sp.getString("sn", null);
        return sn;
    }

    private static void writeSdFileSn(String path, String file, String sn) {
        File snFolder = new File(path);
        if (!snFolder.exists()) {
            snFolder.mkdirs();
        }
        File snFile = new File(path + file);
        FileOutputStream fos = null;
        try {
            if (!snFile.exists()) {
                snFile.createNewFile();
            }
            fos = new FileOutputStream(snFile);
            byte[] bytes = sn.getBytes();
            fos.write(bytes);

        } catch (Exception e) {

        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static String readSdFileSn(String path, String file) {
        File sdSnFile = new File(path + file);
        if (sdSnFile.exists()) {
            FileReader fr = null;
            BufferedReader br = null;
            String snFromFile = null;
            try {
                fr = new FileReader(sdSnFile);
                br = new BufferedReader(fr);
                snFromFile = br.readLine();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fr != null) {
                    try {
                        fr.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return snFromFile;
        }
        return null;
    }

    private static boolean checkSn(String sn) {
        if (sn != null && sn.length() > 4 && sn.matches("[0-9]+")) {
            return true;
        }
        return false;
    }

    private static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist =
                Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
            return sdDir.toString();
        }
        return null;
    }
}
